package com.holike.crm.fragment.report.business;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gallopmark.recycler.adapterhelper.CommonAdapter;

import pony.xcode.tablayout.SlidingTabLayout;
import pony.xcode.tablayout.OnTabSelectListener;

import com.holike.crm.R;
import com.holike.crm.base.BaseFragment;
import com.holike.crm.base.FragmentHelper;
import com.holike.crm.bean.BusinessReferenceTypeBean;
import com.holike.crm.bean.DictionaryBean;
import com.holike.crm.helper.PickerHelper;

import java.util.ArrayList;
import java.util.List;

abstract class DealerMultiPerformanceHelper extends FragmentHelper {

    private Callback mCallback;
    private LinearLayout mContentLayout;
    protected FrameLayout mContainerLayout;
    private String mDimensionOf;// 1:系列 2:花色 3:宅配
    private String mDimensionOfCli; //1定制 2木门 3橱柜
    String mMonth; //时间: 全年,11月,10月.......
    String mShopCode;
    private boolean mIncludeTabLayout = false;
    String mSelectShopName;
    private int mSelectDimensionOfCli;
    private Handler mHandler;

    DealerMultiPerformanceHelper(BaseFragment<?, ?> fragment, Callback callback) {
        super(fragment);
        this.mCallback = callback;
        mContentLayout = obtainView(R.id.ll_content_layout);
        mContainerLayout = obtainView(R.id.fl_container);
        mDimensionOf = getDimensionOf();
        Bundle bundle = fragment.getArguments();
        if (bundle == null) {
            onHttpRequest();
        } else {
            obtainBundleValues(bundle);
            mHandler = new Handler();
            mHandler.postDelayed(this::onHttpRequest, 300);
        }
    }

    abstract String getDimensionOf();

    private void obtainBundleValues(Bundle bundle) {
        mMonth = bundle.getString("month");
        mShopCode = bundle.getString("shopCode");
        mSelectShopName = bundle.getString("shopName");
        mDimensionOfCli = bundle.getString("dimensionOfCli");
    }

    private void onHttpRequest() {
        mCallback.doRequest(mMonth, mDimensionOf, mDimensionOfCli, mShopCode);
    }

    void onSuccess(BusinessReferenceTypeBean bean) {
        mContainerLayout.removeAllViews();
        if (bean == null) {
            noResult();
        } else {
            //动态添加view
            setTabLayout(bean.getMonList());
            LinearLayout llDisplay = obtainDisplay();
            mContainerLayout.addView(llDisplay);
            setTimeDescription(llDisplay, bean.dateToDate);
            setShopLayout(llDisplay, bean.getShopList());
            setDimensionTabList(llDisplay, bean.getDimensionOfCliList());
            setFirstRow(llDisplay);
            setFormData(llDisplay, bean.getResultList());
        }
    }

    private void noResult() {
        LayoutInflater.from(mContext).inflate(R.layout.include_empty_page, mContainerLayout, true);
        mFragment.noResult();
    }

    /*设置月份tab*/
    private void setTabLayout(List<String> monthList) {
        if (monthList.isEmpty()) {
            return;
        }
        if (!mIncludeTabLayout) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.include_common_slidingtablayout, mContentLayout, false);
            SlidingTabLayout tabLayout = view.findViewById(R.id.sliding_tab_layout);
            tabLayout.setupViewPager(view.findViewById(R.id.view_pager), monthList.toArray(new String[0]));
            int selectPosition = -1;
            if (!TextUtils.isEmpty(mMonth)) {
                selectPosition = monthList.indexOf(mMonth);
            } else {
                if (monthList.size() > 1) {  //全年、本月...... 默认显示本月
                    selectPosition = 1;
                }
            }
            if (selectPosition != -1) {
                tabLayout.setCurrentTab(selectPosition);
            }
            tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    if (position >= 0 && position < monthList.size()) {
                        mMonth = monthList.get(position);
                        onHttpRequest();
                    }
                }

                @Override
                public void onTabReselect(int position) {

                }
            });
            mContentLayout.addView(view, 1);
            mIncludeTabLayout = true;
        }
    }

    private LinearLayout obtainDisplay() {
        LinearLayout ll = new LinearLayout(mContext);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        lp.leftMargin = mContext.getResources().getDimensionPixelSize(R.dimen.dp_10);
        lp.rightMargin = mContext.getResources().getDimensionPixelSize(R.dimen.dp_10);
        ll.setLayoutParams(lp);
        ll.setOrientation(LinearLayout.VERTICAL);
        return ll;
    }

    /*时间描述*/
    private void setTimeDescription(LinearLayout llDisplay, String dateToDate) {
        TextView tvDate = new TextView(mContext);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.topMargin = mContext.getResources().getDimensionPixelSize(R.dimen.dp_10);
        tvDate.setLayoutParams(lp);
        tvDate.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimensionPixelSize(R.dimen.textSize_14));
        tvDate.setTextColor(ContextCompat.getColor(mContext, R.color.textColor6));
        tvDate.setText(dateToDate);
        llDisplay.addView(tvDate);
    }

    /*门店*/
    private void setShopLayout(LinearLayout
                                       llDisplay, List<BusinessReferenceTypeBean.ShopBean> shopList) {
        if (!shopList.isEmpty()) {  //没有可选门店
            TextView tvShop = new TextView(mContext);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.topMargin = mContext.getResources().getDimensionPixelSize(R.dimen.dp_12);
            lp.bottomMargin = mContext.getResources().getDimensionPixelSize(R.dimen.dp_12);
            tvShop.setLayoutParams(lp);
            tvShop.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(mContext, R.drawable.choice_down), null);
            tvShop.setCompoundDrawablePadding(mContext.getResources().getDimensionPixelSize(R.dimen.dp_6));
            tvShop.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimensionPixelSize(R.dimen.textSize_14));
            tvShop.setTextColor(ContextCompat.getColor(mContext, R.color.textColor8));
            tvShop.setText(TextUtils.isEmpty(mSelectShopName) ? mContext.getString(R.string.all_stores) : mSelectShopName);
            tvShop.setOnClickListener(v -> selectShop(tvShop, shopList));
            llDisplay.addView(tvShop);
        }
    }

    /*选择门店*/
    private void selectShop(final TextView tvShop, List<
            BusinessReferenceTypeBean.ShopBean> shopList) {
        List<DictionaryBean> optionItems = new ArrayList<>();
        for (BusinessReferenceTypeBean.ShopBean bean : shopList) {
            optionItems.add(new DictionaryBean(bean.shopCode, bean.shopName));
        }
        PickerHelper.showOptionsPicker(mContext, optionItems, ((position, bean) -> {
            mShopCode = bean.id;
            mSelectShopName = bean.name;
            tvShop.setText(mSelectShopName);
            onHttpRequest();
        }));
    }

    private void setDimensionTabList(LinearLayout
                                             llDisplay, List<BusinessReferenceTypeBean.DimensionOfCliBean> dataList) {
        if (!dataList.isEmpty()) {
            RecyclerView rv = new RecyclerView(mContext);
            rv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
            rv.setAdapter(new DimensionTabAdapter(mContext, dataList, mSelectDimensionOfCli));
            llDisplay.addView(rv);
        }
    }

    private final class DimensionTabAdapter extends CommonAdapter<BusinessReferenceTypeBean.DimensionOfCliBean> {

        private int selectPosition;

        DimensionTabAdapter(Context context, List<BusinessReferenceTypeBean.DimensionOfCliBean> dataList, int selectPosition) {
            super(context, dataList);
            this.selectPosition = selectPosition;
        }

        void setSelectPosition(int position) {
            mSelectDimensionOfCli = position;
            this.selectPosition = position;
            notifyDataSetChanged();
        }

        @Override
        protected int bindView(int viewType) {
            return R.layout.item_form_data_tabhost;
        }

        @Override
        public void onBindHolder(RecyclerHolder holder, BusinessReferenceTypeBean.DimensionOfCliBean bean, int position) {
            if (selectPosition == position) {
                holder.setTextColorRes(R.id.tv_role, R.color.color_while);
                holder.itemView.setBackgroundResource(R.drawable.bg_corners5dp_top_coloraccent);
            } else {
                holder.setTextColorRes(R.id.tv_role, R.color.textColor5);
                holder.itemView.setBackgroundResource(R.drawable.bg_corners5dp_top_bg);
            }
            holder.setText(R.id.tv_role, bean.name);
            holder.itemView.setOnClickListener(view -> {
                mDimensionOfCli = bean.type;
                setSelectPosition(position);
                onHttpRequest();
            });
        }
    }

    private void setFirstRow(LinearLayout llDisplay) {
        LayoutInflater.from(mContext).inflate(getFirstRowLayoutResource(), llDisplay, true);
    }

    abstract int getFirstRowLayoutResource();

    private void setFormData(LinearLayout
                                     llDisplay, List<BusinessReferenceTypeBean.DataBean> dataList) {
        RecyclerView rvContent = new RecyclerView(mContext);
        rvContent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        rvContent.setClipToPadding(false);
        rvContent.setPadding(0, 0, 0, mContext.getResources().getDimensionPixelSize(R.dimen.dp_10));
        rvContent.setLayoutManager(new LinearLayoutManager(mContext));
        setFormData(rvContent, dataList);
        llDisplay.addView(rvContent);
    }

    abstract void setFormData(RecyclerView
                                      rvContent, List<BusinessReferenceTypeBean.DataBean> dataList);

    void onFailure(String failReason) {
        mContainerLayout.removeAllViews();
        LayoutInflater.from(mContext).inflate(R.layout.include_empty_page, mContainerLayout, true);
        mFragment.noNetwork(failReason);
    }

    void reload() {
        onHttpRequest();
    }

    interface Callback {
        void doRequest(String month, String dimensionOf, String dimensionOfCli, String shopCode);
    }

    void destroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
